/**
 *
 */
package com.guchenbo.example.dom4j;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.StringWriter;

/**
 * @author Cre.Gu
 *
 */
public class Dom4jTest {

	@Test
	public void createXML() {
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("root");
		Element phone = root.addElement("TelePhone");

		Element nokia = phone.addElement("type");
		nokia.addAttribute("name", "nokia");
		Element price_nokia = nokia.addElement("price");
		price_nokia.addText("599");
		Element operator_nokia = nokia.addElement("operator");
		operator_nokia.addText("CMCC");

		Element xiaomi = phone.addElement("type");
		xiaomi.addAttribute("name", "xiaomi");
		Element price_xiaomi = xiaomi.addElement("price");
		price_xiaomi.addText("699");
		Element operator_xiaomi = xiaomi.addElement("operator");
		operator_xiaomi.addText("ChinaNet");

		// --------
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");

		StringWriter strWtr = new StringWriter();
		XMLWriter xmlWriter = new XMLWriter(strWtr, format);

		try {
			xmlWriter.write(document);
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		System.out.println(strWtr.toString());
	}

}
